package com.company.network;

import com.company.network.base.NetWorkApi;
import com.company.network.bean.BaseResp;
import com.company.network.errorhandler.ExceptionHandle;

import io.reactivex.functions.Function;
import okhttp3.Interceptor;
import okhttp3.Request;

public class WanAndroidApi extends NetWorkApi {

    private static volatile WanAndroidApi instance;

    public static WanAndroidApi getInstance() {
        if (instance == null) {
            synchronized (WanAndroidApi.class) {
                if (instance == null) {
                    instance = new WanAndroidApi();
                }
            }
        }
        return instance;
    }


    public static <T> T getService(Class<T> service) {
        return getInstance().getRetrofit(service).create(service);
    }

    @Override
    protected Interceptor getInterceptor() {
        return (chain) -> {
            Request.Builder builder = chain.request().newBuilder();
            builder.addHeader("type", "wanandroid");
            return chain.proceed(builder.build());
        };
    }

    @Override
    protected <T> Function<T, T> getAppErrorHandler() {
        return (respose) -> {
            if (respose instanceof BaseResp && ((BaseResp) respose).getErrorCode() != 0) {
                ExceptionHandle.ServerException serverException = new ExceptionHandle.ServerException();
                serverException.code = ((BaseResp) respose).getErrorCode();
                serverException.message = ((BaseResp) respose).getErrorMsg();
                throw serverException;
            }
            return respose;
        };
    }

    @Override
    public String getFormal() {
        return "http://wanandroid.com";
    }

    @Override
    public String getTest() {
        return "http://api.douban.com";
    }
}
